package com.sise.thread.Lock;

import java.util.ArrayList;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 作者：idea
 * 日期：2018/6/25
 * 描述：
 */
public class TryLock {

    public ArrayList list=new ArrayList();
    public Lock lock=new ReentrantLock();

    //使用trylock锁的案例
    public void insert(Thread thread){
        if(lock.tryLock()){
            try {
                System.out.println(thread.currentThread().getName()+"获取到了锁");
                for(int i=0;i<100;i++){
                    list.add(i);
                }
            }catch (Exception e){

            }finally {
                System.out.println(thread.currentThread().getName()+"释放了锁");
                lock.unlock();
            }
        }else{
            System.out.println(thread.currentThread().getName()+"获取锁失败了");
        }
    }

    public static void main(String[] args) {
        //使用trylock锁的话，如果获取锁的时候获取失败，可以进行相应的操作
        final TryLock tryLock=new TryLock();
        new Thread(){
            public void run(){
                tryLock.insert(Thread.currentThread());
            }
        }.start();
        new Thread(){
            public void run(){
                tryLock.insert(Thread.currentThread());
            }
        }.start();

    }

}
